<template>
  <div>
    <BusinessTable
      ref="businessTable"
      :search-params="searchParams"
      :table-columns="tableColumns"
      :page-query-url="pageQueryUrl"
      :custom-btn="customBtn"
      @custom-btn="customBtnClick"
    />
    <a-drawer :title="drawerTitle" width="800px" :visible="showDataDrawer" :body-style="{ paddingBottom: '80px' }" :destroyOnClose="true" @close="closeDataDrawer">
      <a-form-model :model="formData" :rules="rules" ref="ruleForm" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="数据源" prop="name">
          <a-input v-model="formData.name" placeholder="请输入数据源" :disabled="edit"></a-input>
        </a-form-model-item>
        <a-form-model-item label="数据源描述" prop="comment">
          <a-input v-model="formData.comment" placeholder="请输入数据源描述"></a-input>
        </a-form-model-item>
        <a-form-model-item label="数据库类型" prop="type">
          <a-input v-model="formData.type" placeholder="请输入数据库类型" default-value="mysql" disabled="true"></a-input>
        </a-form-model-item>
        <a-form-model-item label="域名/ip" prop="host">
          <a-input v-model="formData.host" placeholder="请输入域名/ip"></a-input>
        </a-form-model-item>
        <a-form-model-item label="数据库端口" prop="port">
          <a-input-number v-model="formData.port" placeholder="请输入数据库端口" style="width: 100%"></a-input-number>
        </a-form-model-item>
        <a-form-model-item label="数据库名称" prop="schemaName">
          <a-input v-model="formData.schemaName" placeholder="请输入数据库名称"></a-input>
        </a-form-model-item>
        <a-form-model-item label="数据库账号" prop="username">
          <a-input v-model="formData.username" placeholder="请输入数据库账号"></a-input>
        </a-form-model-item>
        <a-form-model-item label="数据库密码" prop="password">
          <a-input-password v-model="formData.password" placeholder="请输入数据库密码"></a-input-password>
        </a-form-model-item>
      </a-form-model>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }"
      >
        <a-button :style="{ marginRight: '10px' }" type="primary" @click="createDatasource" v-if="!edit">
          提交
        </a-button>

        <a-button :style="{ marginRight: '10px' }" type="primary" @click="updateDatasource" v-else>
          提交
        </a-button>

        <a-button :style="{ marginRight: '10px' }" @click="testConnect">
          测试连接
        </a-button>

        <a-button @click="closeDataDrawer">取消</a-button>
      </div>
    </a-drawer>
  </div>
</template>

<script>
  import BusinessTable from '@/components/BusinessTable';
  import { CUSTOM_BTN, RULES, SEARCH_PARAMS } from '@/views/datasource/index';

  export default {
    name: 'datasource',
    components: { BusinessTable },
    data() {
      return {
        connectionStatus: 0,
        edit: false,
        rules: RULES,
        formData: {
          type: 'mysql',
        },
        labelCol: { span: 4 },
        wrapperCol: { span: 20 },
        drawerTitle: null,
        searchParams: SEARCH_PARAMS,
        tableColumns: [
          {
            title: '数据源',
            dataIndex: 'name',
            key: 'name',
          },
          {
            title: '数据源描述',
            dataIndex: 'comment',
            key: 'comment',
          },
          {
            title: '数据库类型',
            dataIndex: 'type',
            key: 'type',
          },
          {
            title: '域名/ip',
            dataIndex: 'host',
            key: 'host',
          },
          {
            title: '数据库端口',
            dataIndex: 'port',
            key: 'port',
          },
          {
            title: '数据库名称',
            dataIndex: 'schemaName',
            key: 'schemaName',
          },
          {
            title: '数据库账号',
            dataIndex: 'username',
            key: 'username',
          },
          // {
          //   title: '数据库密码',
          //   dataIndex: 'password',
          //   key: 'password',
          // },
          {
            title: '操作',
            dataIndex: 'action',
            customRender: (text, record, index) => {
              return (
                <span class="action-col">
                  <a onClick={() => this.actionClick(record, index)}>编辑</a>
                </span>
              );
            },
            slots: { title: 'action' },
          },
          {
            title: '创建日期',
            dataIndex: 'creationDate',
            key: 'creationDate',
          },
          {
            title: '修改人',
            dataIndex: 'lastUpdatedBy',
            key: 'lastUpdatedBy',
          },
          {
            title: '修改日期',
            dataIndex: 'lastUpdateDate',
            key: 'lastUpdateDate',
          },
        ],
        pageQueryUrl: this.api.datasource.pageQueryDatasource,
        customBtn: CUSTOM_BTN,
        nodeData: null,
        showDataDrawer: false,
      };
    },
    created() {},
    methods: {
      testConnect() {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.formData.url =
              'jdbc:mysql://' +
              this.formData.host +
              ':' +
              this.formData.port +
              '/' +
              this.formData.schemaName +
              '?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true';
            this.axios.post(this.api.datasource.testConnect, this.formData).then((res) => {
              if (res.code === 'ok') {
                this.connectionStatus = 1;
              } else {
                this.connectionStatus = -1;
              }
            });
          }
        });
      },
      createDatasource() {
        if (this.connectionStatus === 0) {
          this.$message.warn('请先测试连接');
          return false;
        }
        if (this.connectionStatus === -1) {
          this.$message.warn('当前连接不可用，请检查');
          return false;
        }
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.formData.url =
              'jdbc:mysql://' +
              this.formData.host +
              ':' +
              this.formData.port +
              '/' +
              this.formData.schemaName +
              '?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true';
            this.axios.post(this.api.datasource.addDatasource, this.formData).then((res) => {
              if (res.code === 'ok') {
                this.$refs.businessTable.reset();
                this.$message.success('添加成功');
                this.showDataDrawer = false;
              }
            });
          }
        });
      },
      updateDatasource() {
        if (this.connectionStatus === 0) {
          this.$message.warn('请先测试连接');
          return false;
        }
        if (this.connectionStatus === -1) {
          this.$message.warn('当前连接不可用，请检查');
          return false;
        }
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.formData.url =
              'jdbc:mysql://' +
              this.formData.host +
              ':' +
              this.formData.port +
              '/' +
              this.formData.schemaName +
              '?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true';
            this.axios.post(this.api.datasource.updateDatasource, this.formData).then((res) => {
              if (res.code === 'ok') {
                this.$refs.businessTable.reset();
                this.$message.success('修改成功');
                this.showDataDrawer = false;
              }
            });
          }
        });
      },
      actionClick(record, index) {
        console.log(index);
        this.formData = record;
        this.drawerTitle = '修改数据源';
        this.edit = true;
        this.showDataDrawer = true;
        this.connectionStatus = 0;
      },
      closeDataDrawer() {
        this.showDataDrawer = false;
      },
      customBtnClick(code) {
        const func = this[code];
        func();
      },
      add() {
        this.formData = { type: 'mysql' };
        this.drawerTitle = '新增数据源';
        this.edit = false;
        this.showDataDrawer = true;
        this.connectionStatus = 0;
      },
      delete() {
        if (this.$refs.businessTable.selectedRowKeys.length === 0) {
          this.$message.warn('请至少选择一行数据');
          return;
        }

        const idList = [];
        for (const index of this.$refs.businessTable.selectedRowKeys) {
          idList.push(this.$refs.businessTable.tableData[index].id);
        }
        this.axios.post(this.api.datasource.deleteDatasource, idList).then((res) => {
          if (res.code === 'ok') {
            this.$refs.businessTable.reset();
          }
        });
      },
    },
  };
</script>

<style scoped></style>
